package com.yanqu.road.server.manager.activity.sonhai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.impl.activity.sonhai.SonHaiConfigDaoImpl;
import com.yanqu.road.dao.impl.servercenter.ActivityDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.commonteam.data.CommonTeamUserData;
import com.yanqu.road.entity.activity.sonhai.config.*;
import com.yanqu.road.entity.activity.sonhai.data.SonHaiPatronsData;
import com.yanqu.road.entity.activity.sonhai.data.SonHaiPlotData;
import com.yanqu.road.entity.activity.sonhai.data.SonHaiRegionData;
import com.yanqu.road.entity.activity.sonhai.param.SonHaiCreatePlotResp;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.player.CrossUserBaseInfo;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.exception.BusinessException;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.server.TempCrossMgr;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeam;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeamActivity;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeamMgr;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossSonHaiActivityMgr extends TempCrossMgr {

    /**
     * logger
     */
    private static Logger logger = LogManager.getLogger(CrossSonHaiActivityMgr.class.getName());

    /**
     * 活动MAP
     */
    private static Map<Integer, Map<Integer, CrossSonHaiActivity>> activityMap = new ConcurrentHashMap<>();

    /**
     * 移除过期活动
     * @return
     * @throws Exception
     */
    @Override
    public boolean removeExpireData() throws Exception {
        Set<Integer> acSet = new HashSet<>();
        long nowTime = System.currentTimeMillis();
        for (Integer activityId : activityMap.keySet()) {
            Map<Integer, CrossSonHaiActivity> groupActivityMap = activityMap.get(activityId);
            if (groupActivityMap != null) {
                for (CrossSonHaiActivity activity : groupActivityMap.values()) {
                    // 展示期过3天后移除内存
                    if (activity == null || activity.getSonHaiConfig() == null || activity.getSonHaiConfig().getActivityInfo() == null ||
                            nowTime > activity.getSonHaiConfig().getActivityInfo().getEndShowTime() * 1000 + 3 * DateHelper.DAY_MILLIONS) {
                        acSet.add(activityId);
                    }
                }
            }
        }
        for (int activityId : acSet) {
            activityMap.remove(activityId);
        }
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        reloadActivityConfig();
        return true;
    }

    /**
     * 刷新配置
     */
    public static void reloadActivityConfig() {
        getLogger().info("CrossSonHaiActivityMgr reloadConfig start");
        for (Map<Integer, CrossSonHaiActivity> groupActivityMap : activityMap.values()) {
            for (CrossSonHaiActivity activity : groupActivityMap.values()) {
                SonHaiConfig configData = activity.getSonHaiConfig();
                if (configData == null) {
                    continue;
                }
                ActivityInfo activityInfo = configData.getActivityInfo();
                if (activityInfo == null) {
                    continue;
                }

                //读取活动
                activityInfo = new ActivityDaoImpl().getActivityInfoByActivityId(activityInfo.getActivityId());
                if (activityInfo == null) {
                    continue;
                }

                if (!ActivityHelper.activityInShowTime(activityInfo)) {
                    continue;
                }
                //构造活动配置
                SonHaiConfig newConfigData = createConfig(activityInfo);
                //刷新配置信息
                activity.refreshConfig(newConfigData);
                getLogger().info("CrossSonHaiActivityMgr reloadConfig success,activityId:{}", activityInfo.getActivityId());
            }
        }
        getLogger().info("CrossSonHaiActivityMgr reloadConfig end");
    }

    @Override
    public boolean reloadData() throws Exception {
        Map<Integer, ActivityInfo> activityInfoMap = ActivityMgr.getOpenCrossActivityMapByType(eActivityType.SonHai.getValue());
        //活动加载进内存
        for (ActivityInfo activityInfo : activityInfoMap.values()) {
            //查询活动分组
            Map<Integer, UnionActivityGroup> activityGroupMap = Cross2UnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
            if (null != activityGroupMap) {
                for (UnionActivityGroup activityGroup : activityGroupMap.values()) {
                    if (activityGroup.getCrossServerId() == CrossBaseServer.getInstance().getServerId()) {
                        getActivity(activityGroup.getActivityId(), activityGroup.getGroupId());
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        for (Map<Integer, CrossSonHaiActivity> groupActivityMap : activityMap.values()) {
            for (CrossSonHaiActivity activity : groupActivityMap.values()) {
                try {
                    activity.save();
                }catch (Exception e){
                    getLogger().error("CrossSonHaiActivityMgr activity {} save err", activity.getSonHaiConfig().getActivityInfo().getActivityId(), e.getCause());
                }
            }
        }
        return true;
    }

    public static Logger getLogger() {
        return logger;
    }

    /**
     * 获取活动MAP
     * @return
     */
    public static Map<Integer, Map<Integer, CrossSonHaiActivity>> getActivityMap() {
        return activityMap;
    }

    /**
     * 获取活动
     * @param activityId
     * @param groupId
     * @return
     */
    public static CrossSonHaiActivity getActivity(int activityId, int groupId) {
        Map<Integer, CrossSonHaiActivity> groupActivityMap = activityMap.get(activityId);
        if (groupActivityMap != null) {
            CrossSonHaiActivity activityInfo = groupActivityMap.get(groupId);
            if (activityInfo != null) {
                return activityInfo;
            }
        }
        //初始化活动
        return initActivity(activityId, groupId);
    }

    /**
     * 初始化活动
     * @param activityId
     * @return
     */
    private static CrossSonHaiActivity initActivity(int activityId, int groupId) {
        synchronized (activityMap) {
            Map<Integer, CrossSonHaiActivity> groupActivityMap = activityMap.computeIfAbsent(activityId, k -> new ConcurrentHashMap<>());
            CrossSonHaiActivity activity = groupActivityMap.get(groupId);
            if (activity != null) {
                return activity;
            }
            // 读配置 获取活动信息 保证有活动信息
            ActivityInfo activityInfo = ActivityMgr.getActivityInfoMayLoadDB(activityId);
            if (activityInfo == null) {
                return null;
            }
            //不在展示期（+3天）也不处理了
            if (!ActivityHelper.activityInShowTime(activityInfo)) {
                return null;
            }
            //创建配置
            SonHaiConfig sonHaiConfig = createConfig(activityInfo);
            //创建活动
            activity = new CrossSonHaiActivity(sonHaiConfig, groupId);
            groupActivityMap.put(groupId, activity);
            return activity;
        }
    }

    /**
     * 创建配置
     * @param activityInfo
     * @return
     */
    private static SonHaiConfig createConfig(ActivityInfo activityInfo) {
        SonHaiConfigDaoImpl dao = new SonHaiConfigDaoImpl();
        //获取活动config
        List<Integer> activityIdList = new ArrayList<>();
        activityIdList.add(activityInfo.getActivityId());
        //condition
        Map<String, ActivityConfig> activityConfigMap = ActivityBussiness.getActivityConfigMap(activityIdList).get(activityInfo.getActivityId());
        //mall
        Map<Integer, MallInfo> mallInfoMap = ActivityBussiness.getActivityMallInfoMap(activityIdList).get(activityInfo.getActivityId());
        //事件配置
        Map<Integer, SonHaiEventConfig> eventConfigMap = dao.getEventConfigMap(activityInfo.getActivityId());
        //区域配置
        Map<Integer, SonHaiFloorConfig> floorConfigMap = dao.getFloorConfigMap(activityInfo.getActivityId());
        //BUFF配置
        Map<Integer, SonHaiBuffConfig> buffConfigMap = dao.getBuffConfigMap(activityInfo.getActivityId());
        //怪配置
        Map<Integer, SonHaiMonsterConfig> monsterConfigMap = dao.getMonsterConfigMap(activityInfo.getActivityId());
        //蛋配置
        Map<Integer, SonHaiEggConfig> eggConfigMap = dao.getEggConfigMap(activityInfo.getActivityId());
        //地图配置
        Map<Integer, SonHaiMapConfig> mapConfigMap = dao.getMapConfigMap(activityInfo.getActivityId());
        //蛋名
        Map<Integer, SonHaiEggNameConfig> eggNameConfigMap = dao.getEggNameConfigMap(activityInfo.getActivityId());
        return new SonHaiConfig(activityInfo, activityConfigMap, mallInfoMap, eventConfigMap, floorConfigMap, buffConfigMap, monsterConfigMap, eggConfigMap, mapConfigMap, eggNameConfigMap);
    }

    /**
     * 获取区域
     * @param activityId
     * @param groupId
     * @param teamId
     * @param regionId
     * @return
     */
    public static SonHaiRegionData getRegionData(int activityId, int groupId, int teamId, int regionId) {
        CrossSonHaiActivity activity = getActivity(activityId, groupId);
        if (activity != null) {
            return activity.getRegionData(teamId, regionId);
        }
        return null;
    }

    /**
     * 获取玩家
     * @param activityId
     * @param groupId
     * @param userId
     * @return
     */
    public static CrossSonHaiUser getUser(int activityId, int groupId, long userId) {
        CrossSonHaiActivity activity = getActivity(activityId, groupId);
        if (activity != null) {
            return activity.getUser(userId);
        }
        return null;
    }

//    public static void test() {
//        for (Map<Integer, CrossSonHaiActivity> groupActivityMap : activityMap.values()) {
//            for (Map.Entry<Integer, CrossSonHaiActivity> entry  : groupActivityMap.entrySet()) {
//                CrossSonHaiActivity activity = entry.getValue();
//                int groupId = entry.getKey();
//                for (int i = 1; i <= 2000; i++) {
//                    long userId = i;
//                    logger.info("/***********************************山海伏兽-压测-start：{}***********************************/", userId);
//                    //玩家userBase
//                    CrossUserBaseInfo userBaseInfo = CrossUserMgr.getCrossUserBaseInfo(101001970008485L);
//                    CrossUserMgr.updateUserBaseInfo(userId, userBaseInfo.getUserBaseInfo());
//
//                    try {
//                        //创建队伍
//                        CommonTeamActivity teamActivity = CommonTeamMgr.getActivity(activity.getSonHaiConfig().getActivityInfo().getActivityId(), groupId);
//                        CommonTeamUserData userData = teamActivity.getUserDataOrCreate(userId, 1000);
//                        //创建队伍
//                        CommonTeam team = new CommonTeam (
//                                activity.getSonHaiConfig().getActivityInfo().getActivityId(),
//                                groupId,
//                                userData.getServerId(),
//                                10000 + i,
//                                String.valueOf(10000 + i),
//                                userData.getUserId(),
//                                userData.getUserName(),
//                                userData.getScore()
//                        );
//                        Map<Integer, CommonTeam> teamMap = teamActivity.getTeamMap();
//                        teamMap.put(team.getTeamId(), team);
//                        //添加成员
//                        team.addMemberData(userData);
//                        //初始化玩家
//                        activity.enterActivity(userId, 66699991L, 163254154751L, 100);
//                        CrossSonHaiUser user = activity.getUser(userId);
//                        logger.info("山海伏兽-压测-初始化玩家成功：{}", userId);
//
//                        //探索,200个事件
//                        int num = 0;
//                        for (int x = 0; x < 20; x++) {
//                            for (int y = 0; y < 20; y++) {
//                                SonHaiCreatePlotResp createPlotResp = activity.createPlot(user.getRegionData(), userId, x, y, false, 0, null);
//                                if (createPlotResp.getPlotData() != null) {
//                                    num++;
//                                }
//                            }
//                        }
//                        logger.info("山海伏兽-压测-地块数：{}", num);
//                        logger.info("/***********************************山海伏兽-压测-end：{}***********************************/", userId);
//                    } catch (BusinessException e) {
//                        logger.info("/***********************************山海伏兽-压测-异常：{}***********************************/", userId);
//                    }
//                }
//            }
//        }
//    }
}
